//
//  UIViewController+WSCategory.m
//  WSBaseKit
//
//  Created by zhangcong on 2020/8/14.
//  Copyright © 2020 zhangcong. All rights reserved.
//

#import "UIViewController+WSCategory.h"
#import <objc/runtime.h>
#import "WSConst.h"
@implementation UIViewController (WSCategory)

-(void) showProgress:(MBProgressHUDMode) mode msg:(NSString*) msg {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view addSubview:hud];
    [self.view bringSubviewToFront:hud];
    
    hud.detailsLabel.text = msg;
    hud.mode = mode;
    hud.removeFromSuperViewOnHide = YES;
}

- (void)showTips:(NSString *)msg {
    [self showTips:msg afterDelay:2];
}

- (void)showTips:(NSString *)msg afterDelay:(NSTimeInterval)delay {
    [self hiddenProgress];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view addSubview:hud];
    [self.view bringSubviewToFront:hud];
    hud.userInteractionEnabled = NO;
    hud.detailsLabel.text = msg;
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud hideAnimated:YES afterDelay:delay];
    
    self.progressHud = hud;
}

- (void)showLoader:(NSString *)msg {
    
    [self hiddenProgress];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    [self.view bringSubviewToFront:hud];
    hud.userInteractionEnabled = NO;
    hud.detailsLabel.text = msg;
    [hud showAnimated:YES];
    
    self.progressHud = hud;
}

- (void) removeMBProgressHUD {
    [self hiddenProgress];
}

-(void) hiddenProgress {
    [self.progressHud hideAnimated:NO];
    [self removeExistHUD];
}

- (void)removeExistHUD {
    dispatch_async(dispatch_get_main_queue(), ^{
        for (UIView * view in self.view.subviews) {
            if ([view isKindOfClass:[MBProgressHUD class]]) {
                MBProgressHUD * HUD = (MBProgressHUD *)view;
                [HUD removeFromSuperview];
                HUD = nil;
            }
        }
        self.progressHud = nil;
    });
}

- (void)showError:(NSError *)error {
    [self showError:error complete:nil];
}

- (void)showError:(NSError *)error complete:(void(^)(void))complete{
    NSString *stringError = [[error userInfo] objectForKey:NSLocalizedDescriptionKey];
    [self showTips:stringError afterDelay:2.5];
}

-(void) hideKeyboard {
    [self.view endEditing:YES];
}

- (void)setProgressHud:(MBProgressHUD *)progressHud
{
    objc_setAssociatedObject(self, @"progressHud", progressHud, OBJC_ASSOCIATION_RETAIN);
}

- (MBProgressHUD *)progressHud
{
    return objc_getAssociatedObject(self, @"progressHud");
}

- (void)pushViewController:(NSString *)identifier block:(void (^)(UIViewController *viewController))block {
    const char *className = [identifier cStringUsingEncoding:NSASCIIStringEncoding];
    
    Class newClass = objc_getClass(className);
    if (!newClass) {
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        objc_registerClassPair(newClass);
    }
    
    if ([newClass isSubclassOfClass:[UIViewController class]]) {
        UIViewController * instance = (UIViewController *)[[newClass alloc] init];
        
        instance.hidesBottomBarWhenPushed = YES;
        if (block) {
            block(instance);
        }
        NSLog(@"self.navigation = %@",self.navigationController);
        [self.navigationController pushViewController:instance animated:YES];
    }
    else {
        [self showTips:@"PushError"];
    }
}

- (void)pushViewControllerWithIdentifier:(NSString *)identifier storyboardName:(NSString *)storyboardName block:(void (^)(UIViewController *))block{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:storyboardName?:@"main" bundle:nil];
    UIViewController * vc = [storyBoard instantiateViewControllerWithIdentifier:identifier];
    
    if (vc) {
        vc.hidesBottomBarWhenPushed = YES;
        if (block) {
            block(vc);
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        [self showTips:@"PushError"];
    }
}


#pragma mark - 给vc添加属性  控制是否支持手势返回
- (void)setForbidPanBack:(BOOL)forbidPanBack{
    objc_setAssociatedObject(self, @"forbidPanBack", @(forbidPanBack), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)forbidPanBack {
    return [objc_getAssociatedObject(self, @"forbidPanBack") boolValue];
}

#pragma mark - 导航栏按钮
+ (void)load{
    Method s1 = class_getInstanceMethod([self class], @selector(viewDidAppear:));
    Method s2 = class_getInstanceMethod([self class], @selector(viewDidAppearSwizzle));
    method_exchangeImplementations(s1, s2);
    
    Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method method2 = class_getInstanceMethod([self class], @selector(deallocSwizzle));
    method_exchangeImplementations(method1, method2);
    
    Method ss1 = class_getInstanceMethod([self class], @selector(viewDidLoad));
    Method ss2 = class_getInstanceMethod([self class], @selector(viewDidLoadSwizzle));
    method_exchangeImplementations(ss1, ss2);
}
    
    
#pragma mark - nav
- (UIBarButtonItem *)loadRightItemWithImage:(NSString *)image action:(SEL)action{
    return [self loadItemWithImage:image action:action orientation:@"right" isImage:YES];
}
- (UIBarButtonItem *)loadLeftItemWithImage:(NSString *)image action:(SEL)action{
    return [self loadItemWithImage:image action:action orientation:@"left" isImage:YES];
}
- (UIBarButtonItem *)loadLeftItemWithTitle:(NSString *)title action:(SEL)action{
    return [self loadItemWithImage:title action:action orientation:@"left" isImage:NO];
}
- (UIBarButtonItem *)loadRightItemWithTitle:(NSString *)title action:(SEL)action{
    return [self loadItemWithImage:title action:action orientation:@"right" isImage:NO];
}

- (void)loadLeftItemWithImage:(NSString *)image Title:(NSString *)title action:(SEL)action{
    UIBarButtonItem *saveItem;
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(5, 0, 60,44);
    [saveBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitle:title forState:UIControlStateNormal];
    [saveBtn setImage:WSImage(image) forState:UIControlStateNormal];
    
    saveItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    self.navigationItem.leftBarButtonItem = saveItem;
}
    
- (void)loadLeftItemWithRightImage:(NSString *)image LeftTitle:(NSString *)title action:(SEL)action{
    UIBarButtonItem *saveItem;
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(5, 0, 60,44);
    //    saveBtn.titleLabel.sd_layout.leftEqualToView(saveBtn).centerYEqualToView(saveBtn).heightIs(16);
    //    [saveBtn.titleLabel setSingleLineAutoResizeWithMaxWidth:60-14];
    //    saveBtn.imageView.sd_layout.leftSpaceToView(saveBtn.titleLabel, 0).centerYEqualToView(saveBtn).heightIs(14).widthIs(14);
    [saveBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitle:title forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [saveBtn setImage:WSImage(image) forState:UIControlStateNormal];
    
    saveItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    self.navigationItem.leftBarButtonItem = saveItem;
}
    
- (UIBarButtonItem *)loadItemWithImage:(NSString *)image action:(SEL)action orientation:(NSString *)orientation isImage:(BOOL)isImage{
    UIBarButtonItem *saveItem;
    if (isImage) {
        UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage * img = WSImage(image);
        saveBtn.frame = CGRectMake(0, 0, img.size.width,44);
        if(![orientation isEqualToString:@"right"] ){
            saveBtn.frame = CGRectMake(-9, 0,  img.size.width, 44);
        }
        
        [saveBtn setImage:WSImage(image) forState:UIControlStateNormal];
        [saveBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
        saveItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    }else{
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:image forState:UIControlStateNormal];
        
        //        [btn setTitleColor:kUIColorWithRGB(0xdb4545) forState:UIControlStateNormal];
        [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
        btn.titleLabel.shadowColor =  [UIColor colorWithRed:37.0/255.0 green:144/255.0 blue:145.0/255.0 alpha:1];
        btn.titleLabel.shadowOffset = CGSizeMake(1, 1);
        
        CGSize titleSize = [image sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
        [btn setFrame:CGRectMake(0, 0, (titleSize.width + 10), 44)];
        
        [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
        saveItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        saveItem.width = -5;
    }
    if ([orientation isEqualToString:@"right"]) {
        if(!isImage)
        [self setRightBarButtonItem:saveItem isImage:NO];
        else
        [self setRightBarButtonItem:saveItem isImage:YES];
    }else{
        self.navigationItem.leftBarButtonItem = saveItem;
    }
    return saveItem;
}
    
- (void)loadItemWithFirstImage:(NSString *)image1 firstAction:(SEL)action1 secondImage:(NSString *)image2 secondAction:(SEL)action2 orientation:(NSString *)orientation{
    UIBarButtonItem *buttonItem1 ;
    UIBarButtonItem *buttonItem2 ;
    
    {
        UIButton *saveBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        saveBtn1.frame = CGRectMake(0, 0, 30,44);
        
        //saveBtn.showsTouchWhenHighlighted = YES;
        [saveBtn1 addTarget:self action:action1 forControlEvents:UIControlEventTouchUpInside];
        
        buttonItem1 = [[UIBarButtonItem alloc] initWithCustomView:saveBtn1];
        
        UIImageView *imageImv = [[UIImageView alloc] initWithFrame:saveBtn1.bounds];
        
        imageImv.image = WSImage(image1);
        imageImv.contentMode = UIViewContentModeCenter;
        [saveBtn1 addSubview:imageImv];
    }
    
    {
        UIButton *saveBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        saveBtn2.frame = CGRectMake(0, 0, 32,44);
        
        //saveBtn.showsTouchWhenHighlighted = YES;
        [saveBtn2 addTarget:self action:action2 forControlEvents:UIControlEventTouchUpInside];
        
        buttonItem2 = [[UIBarButtonItem alloc] initWithCustomView:saveBtn2];
        
        UIImageView *imageImv = [[UIImageView alloc] initWithFrame:saveBtn2.bounds];
        
        imageImv.image = WSImage(image2);
        imageImv.contentMode = UIViewContentModeCenter;
        [saveBtn2 addSubview:imageImv];
    }
    
    if ([orientation isEqualToString:@"left"])
    [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects: buttonItem1,buttonItem2,nil]];
    else
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects: buttonItem1,buttonItem2,nil]];
}
    
- (void)setRightBarButtonItem:(UIBarButtonItem *)_rightBarButtonItem isImage:(BOOL)isimage
    {
        
        UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        
        negativeSeperator.width = isimage ? 0 : -10;
        //        negativeSeperator.width = -16;//此处修改到边界的距离，请自行测试
        
        if (_rightBarButtonItem)
        {
            [self.navigationItem setRightBarButtonItems:[[NSArray alloc] initWithObjects:negativeSeperator, _rightBarButtonItem,nil]];
        }
        else
        {
            [self.navigationItem setRightBarButtonItems:[[NSArray alloc] initWithObjects:negativeSeperator,nil]];
        }
    }
    
- (void)setRightItemWithTitle:(NSString *)title action:(SEL)action {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:action];
    self.navigationItem.rightBarButtonItem = item;
}
    


@end
